package com.starblink.android.basic.util;

import android.content.Context;
import android.view.View;
import android.widget.PopupWindow;

import com.starblink.basic.util.log.YYLogUtils;

import java.util.logging.Logger;

public class CustomPopupWindow extends PopupWindow {
    private OnBackPressListener mOnBackPressListener;

    public CustomPopupWindow(View contentView, int width, int height, boolean focusable) {
        super(contentView, width, height, focusable);
    }

    public CustomPopupWindow(Context context) {
        super(context);
    }

    public CustomPopupWindow() {
    }

    public CustomPopupWindow(View contentView) {
        super(contentView);
    }

    public CustomPopupWindow(int width, int height) {
        super(width, height);
    }

    public CustomPopupWindow(View contentView, int width, int height) {
        super(contentView, width, height);
    }

    @Override
    public void dismiss() {
        StackTraceElement[] stackTrace = new Exception().getStackTrace();
        for (int i = 0; i < stackTrace.length; i++) {
            YYLogUtils.e("key = " + stackTrace[i]);
        }

        if (stackTrace.length >= 2 && "dispatchKeyEvent".equals(stackTrace[1].getMethodName())) {
            //按了返回键
            if (mOnBackPressListener != null) {
                YYLogUtils.e("按了返回键");
                mOnBackPressListener.onBack();
            } else {
                dismiss2();
            }

        } else {
            //点击外部或者点击关闭调用了dismiss,直接让弹窗消失
            dismiss2();
        }

    }

    //让弹窗消失
    private void dismiss2() {
        super.dismiss();
    }


    public OnBackPressListener getOnBackPressListener() {
        return mOnBackPressListener;
    }

    public void setOnBackPressListener(OnBackPressListener onBackPressListener) {
        this.mOnBackPressListener = onBackPressListener;
    }

    public interface OnBackPressListener {
        void onBack();
    }
}
